<template>
  <el-container class="login-container">
    <el-main>
      <el-card class="login-card">
        <h2 class="title">登录</h2>
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
import { ref } from 'vue';
import { login } from '../../api/login/index.ts'
import { useRouter } from 'vue-router'; // 引入 useRouter
export default {
  name: 'Login',
  setup() {
    const form = ref({
      username: '',
      password: ''
    });
    const router = useRouter();
    const rules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    };

    const loading = ref(false);

    const handleLogin = () => {
      loading.value = true;
    //   登录
      login(form.value).then(res => {
        // 判断 登录是否成功
        console.log(res,"res")
        if(res.code === 200){

        //   路由跳转
          router.push('/')
          loading.value = false;
        }else{
          loading.value = false;
        }
      })
          .catch(err => {
            console.log(err, '登录失败:')
            loading.value = false;
          })
    };

    return {
      form,
      rules,
      loading,
      handleLogin
    };
  }
};
</script>
<style scoped>
html, body, #app {
  height: 100%; /* 确保整个页面的高度为 100% */
  margin: 0;
}

.login-container {
  height: 100vh; /* 视口高度 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */

  background-color: #f4f4f4; /* 可自定义背景颜色 */
}

.login-card {
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  background-color: white;
  border-radius: 8px; /* 卡片的圆角 */
/*卡片居中*/
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 400px;
  min-width: auto;
}

.title {
text-align: center;
margin-bottom: 20px;
font-size: 24px;
}

.el-form {
width: 100%;
}

.el-form-item {
margin-bottom: 20px;
}
</style>
